package com.android.openapp.services;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.json.JSONException;

import com.android.openapp.R;
import com.android.openapp.data.Agriturismo;
import com.android.openapp.data.Architettura;
import com.android.openapp.data.Fiera;
import com.android.openapp.data.Museo;
import com.android.openapp.data.NLStorici;
import com.android.openapp.data.Ostello;
import com.android.openapp.data.Place;
import com.android.openapp.ui.Utils;
import com.socrata.api.HttpConnection;
import com.socrata.api.RequestException;
import com.socrata.api.Response;
import com.socrata.data.View;
import com.socrata.data.View.Column;

import com.socrata.util.Variables;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;

public class SearchData extends AsyncTask<Boolean, String, Integer[]>{

	Context mUIContext;
	Context mServiceContext;
	HttpConnection mConnection;
	String query;
	ProgressDialog pd;
	
	/**
	 * Costruttore che riceve il context della Activity
	 * Puo' essere usato per chiamare metodi della UI
	 * (creare Toast e Dialog)
	 * @param serviceContext il Service chiamante
	 * @param UIContext se presente, la Activity
	 */
	public SearchData(Context serviceContext, Context UIContext, HttpConnection connection,String query){
		mServiceContext = serviceContext;
		mUIContext = UIContext;
		mConnection = connection;
		this.query=query;
	}
	
	@Override
	protected void onPreExecute() {
		// TODO Auto-generated method stub
		super.onPreExecute();
		String text = mUIContext.getResources().getString(R.string.in_search);
		pd = ProgressDialog.show(mUIContext, null, text);
	}
	
	@Override
	protected Integer[] doInBackground(Boolean... params) {
		ArrayList<Place> list=new ArrayList<Place>();
		Integer result=0;
		Integer cycle=0;
		
		for(int i=0;i<Place.datasetM.length;i++){
			if (params[i]){
				cycle++;
				Column den=Place.listmetadati.get(i).getColumnByIdentifier(mUIContext.getResources().getStringArray(R.array.DENOMINAZIONE)[i]);
				Column tip=Place.listmetadati.get(i).getColumnByIdentifier(mUIContext.getResources().getStringArray(R.array.TIPOLOGIA)[i]);
				Column ind=Place.listmetadati.get(i).getColumnByIdentifier(mUIContext.getResources().getStringArray(R.array.INDIRIZZO)[i]);
				Column field=Place.listmetadati.get(i).getColumnByIdentifier(mUIContext.getResources().getStringArray(R.array.FIELD_2)[i]);
				
				String json=
					"{query:{"+
						  "'originalViewId': "+Place.datasetM[i].toLowerCase()+","+
						  "'name': "+Place.datasetM[i].toLowerCase()+","+
						  "'query': {"+
						    "'filterCondition': {"+
						      "'type': 'operator',"+
						      "'value': 'OR',"+
						      "'children': ["+
						        "{"+
						          "'type': 'operator',"+
						          "'value': 'CONTAINS',"+
						          "'children': ["+
						            "{"+
						              "'columnId':"+ den.getId()+","+
						              "'type': 'column'"+
						            "},"+
						            "{"+
						              "'type': 'literal',"+
						              "'value': "+query+
						            "}"+
						          "]"+
						        "},"+
						        "{"+
						          "'type': 'operator',"+
						          "'value': 'CONTAINS',"+
						          "'children': ["+
						            "{"+
						              "'columnId': "+field.getId()+","+
						              "'type': 'column'"+
						            "},"+
						            "{"+
						              "'type': 'literal',"+
						              "'value': "+query+
						            "}"+
						          "]"+
						        "},"+
						        "{"+
						          "'type': 'operator',"+
						          "'value': 'CONTAINS',"+
						          "'children': ["+
						            "{"+
						              "'columnId': "+tip.getId()+","+
						              "'type': 'column'"+
						            "},"+
						            "{"+
						              "'type': 'literal',"+
						              "'value': "+query+
						            "}"+
						          "]"+
						        "},"+
						        "{"+
						          "'type': 'operator',"+
						          "'value': 'CONTAINS',"+
						          "'children': ["+
						           " {"+
						              "'columnId': "+ind.getId()+","+
						              "'type': 'column'"+
						            "},"+
						            "{"+
						              "'type': 'literal',"+
						              "'value': "+query+
						            "}]}] }}}}";

				//String url="https://dati.lombardia.it/api/views/"+Place.datasetM[i].toLowerCase()+"/rows.xml?search="+query;
				Response r = mConnection.post("https://dati.lombardia.it/api/views/INLINE/rows.json?method=getRows&start=0&length=100",json);
				
				if(r!=null){
					List<View.Row> row1;
					try {
						row1 = Place.listmetadati.get(i).getRows(r);
				
				
				
						if(row1!=null){
							result++;
					
					
				Place loc = null;
				Log.d("Place",Integer.toString(i));
				for(View.Row temp : row1){
				
					switch(i){
								case 0: loc=new Museo(temp);
					
								break;
						case 1: loc=new Ostello(temp);
								break;
						case 2: try {
							loc=new Architettura(temp);
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							break;
						}
								break;
						case 3: loc=new Agriturismo(temp);
								break;
						case 4: loc=new NLStorici(temp);
								break;
						case 5: loc=new Fiera(temp);
								break;
					

					}
					if(loc != null){
						for(Place l : Place.list_bookmarks){
							if(l.getDenominazione().equals(loc.getDenominazione())&&l.getAddress().equals(loc.getAddress()))
								loc.bookmark=1;
						}
						list.add(loc);
						Log.d("Place",loc.getDenominazione());
					}
			}
		}
				} catch (RequestException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		}
	}
	}
		synchronized (Place.lista) {
			Collections.sort(list);
			Place.setPlaces(list);
			//Place.temp=list;
			Log.d("Sync lista","ok");
		}
		Integer[] array={result,cycle};
		return array;
}
	@Override
	protected void onPostExecute(Integer[] result) {
		super.onPostExecute(result);
		
		pd.dismiss();
		
		Intent i;
		if(result[0] == result[1]){
			i = new Intent(Variables.DOWNLOAD_FINISHED);
			i.putExtra(Variables.DOWNLOAD_RESULT, Variables.NO_ERROR);
			Utils.showToast(mUIContext, "Scaricamento Places eseguito con successo");
			result[0]=0;
			result[1]=0;
		}
		else{
			i = new Intent(Variables.DOWNLOAD_FINISHED);
			i.putExtra(Variables.DOWNLOAD_RESULT, Variables.DOWNLOAD_ERROR);
			Utils.showToast(mUIContext, "Scaricamento Places eseguito con errori");
			result[0]=0;
			result[1]=0;
		}
		mServiceContext.sendBroadcast(i);
	}

}
